package com.itqf.mybatis;

import com.itqf.bean.Role;
import com.itqf.bean.User;
import com.itqf.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

/**
 * projectName: mybatis2103
 *
 * @author: 赵伟风
 * time: 2021/6/24 10:14
 * description:
 */
public class UseMybatisSelect {

    public static void main(String[] args) throws Exception{


        //1.读取配置
        InputStream stream = Resources.getResourceAsStream("mybatis_config.xml");
        //2.创建sqlsesssionfactorybuilder
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        //3.创建sqlsessionfactory
        SqlSessionFactory sqlSessionFactory = factoryBuilder.build(stream);
        //4.创建sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //5.获取mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User query = mapper.query(1);
        System.out.println("query = " + query);

        List<User> users = mapper.queryRole();

        for (User user : users) {
            System.out.println("------------------");
            System.out.println("用户信息");
            System.out.println("user = " + user);
            System.out.println("用户详情信息");
            System.out.println("user.getDetail() = " + user.getDetail());
            System.out.println("用户角色信息");
            List<Role> roles = user.getRoles();
            if (roles != null) {

                for (Role role : roles) {
                    System.out.println("role = " + role);
                    System.out.println("角色对应的薪水:");
                    System.out.println("role = " + role.getSalary());
                }

            }else{
                System.out.println("用户没有角色!");
            }

            System.out.println("------------------");
        }


        //7.关闭资源
        sqlSession.close();

    }
}
